# coding: utf8
__author__ = 'tony'

import random
import json
import urllib2
import config


class UmengProtocol(object):

	@classmethod
	def make_body_launch(cls, user):
		"""
		生成启动属性
		:param user: 用户
		:return: launch字典
		:rtype: dict
		"""
		date = user.launch_date
		time = user.launch_time
		return {
			'date': date,
			'session_id': user.launch_session_id,
			'time': time,
		}

	@classmethod
	def make_body_terminate(cls, user, activities, dntr=None, uptr=None):
		"""
		生成上次使用属性
		:param user: 用户
		:param activities: 页面访问路径
		:param dntr: 下载流量
		:param uptr: 上传流量
		:return: terminate字典
		:rtype: dict
		"""
		return {
			'duration': user.terminate_duration,
			'session_id': user.terminate_session_id,
			'time': user.terminate_time,
			'date': user.terminate_date,
			'activities': activities,
			'dntr': int(dntr) if dntr is not None else random.randint(3000, 8000),
			'uptr': int(uptr) if uptr is not None else random.randint(2000, 4000),
		}

	@classmethod
	def make_header(cls, user):
		"""
		生成头部信息
		:param user: 用户
		:return: header 字典
		:rtype: dict
		"""
		device = user.device
		app = device._app
		umeng = app._umeng_sdk
		return {
			'appkey': app.appkey,
			'package_name': app.package_name,
			'app_version': app.app_version,
			'channel': app.channel,
			'version_code': app.version_code,
			'device_model': device.device_model,
			'timezone': device.time_zone,
			'device_name': device.device_name,
			'mc': device.mc,
			'resolution': device.resolution,
			'carrier': device.carrier,
			'device_board': device.device_board,
			'device_manufacturer': device.device_manufacturer,
			'cpu': device.cpu,
			'device_id': device.device_id,
			'device_brand': device.device_brand,
			'access': device.access,
			'access_subtype': device.access_subtype,
			'country': device.country,
			'idmd5': device.idmd5,
			'device_manutime': device.device_manutime,
			'os': device.os,
			'os_version': device.os_version,
			'device_manuid': device.device_manuid,
			'language': device.language,
			'sdk_type': umeng.sdk_type,
			'sdk_version': umeng.sdk_version,
			'req_time': random.randint(50, 300)
		}

	@classmethod
	def make_protocol(cls, launches, terminates, header):
		"""
		生成完整的报文字典
		:param launches: launch字典列表
		:param terminates: terminate字典列表
		:param header: header字典
		:return: 协议字典
		:rtype: dict
		"""
		return {
			'header': header,
			'body': {
				'launch': launches,
				'terminate': terminates,
			}
		}

	@classmethod
	def assemble(cls, virtualuser, activities):
		"""
		装配请求
		:param virtualuser: <VirtualUser>
		:param activities: <list: 访问路径>
		:return: <Request: 装配好的协议请求>
		"""
		launches = [cls.make_body_launch(virtualuser)]
		terminates = [cls.make_body_terminate(virtualuser, activities)]
		header = cls.make_header(virtualuser)
		protocol = cls.make_protocol(launches=launches, terminates=terminates, header=header)
		protocol = json.dumps(protocol)
		data = 'content=%s' % protocol
		req = urllib2.Request(config.umeng_entrance, data)
		return req


class BaiduProtocol(object):
	"""
	百度统计
	"""
	@classmethod
	def assemble(cls, virtualuser, activities):
		"""
		装配协议内容
		:param virtualuser: <VirtualUser>
		:param activities: <DataSet: 访问路径数据集>
		:return: <tuple: (<str: url>, <str: payload>, <dict: headers>)>
		"""
		import time
		from tools import random
		import StringIO
		import gzip

		time_s = int(time.time() * 1000)
		time_e = time_s + random.randint(1, 5) * 60 * 1000
		time_i = time_e + random.randint(1, 5) * 60 * 1000
		time_ss = time_i + random.randint(5, 20) * 60 * 1000
		time_t = time_ss + random.randint(1, 5) * 60 * 1000
		phone = virtualuser.device

		protocol = {
			'ex': [],
			'pr': [
				{
					'e': time_e,
					's': time_s,
					'c': 1,
					'i': time_i,
					'p': [
						{
							'n': activities.random_data,
							'd': 693,
							'ps': 3
						}
					]
				}
			],
			'ev': [],
			'he': {
				'd': phone.device_id,
				'op': '46000',
				'wl': '%s_%s' % (random.random_str(15), random.random_str(2, '123456789')),
				'c': virtualuser.channel,
				'sq': 0,
				'a': virtualuser.launch_datetime.strftime('%Y%m%d'),
				'n': '1.7.7alpha',
				'o': phone.os,
				'l': 'WIFI',
				'm': phone.device_model,
				'k': 'ab47e4db25',
				# 'k': 'a2d1a3da78', # test
				'h': phone.height,
				'i': '%s|%s' % (random.random_str(32, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'), random.random_str(15, '1234567890')),
				'w': phone.width,
				'v': '3.4',
				'gl': '',
				't': time_t,
				's': '19',
				'cl': '%s_%s_%s' % (random.random_str(9, '123456789'), random.random_str(5, '123456789'), random.random_str(1, '123456789')),
				'ss': time_ss
			}
		}

		protocol = json.dumps(protocol)
		protocol.replace(' ', '')

		zbuf = StringIO.StringIO()
		zf = gzip.GzipFile(mode='wb', fileobj=zbuf)
		zf.write(protocol)
		zf.close()
		content = zbuf.getvalue()
		zbuf.close()
		return config.baidu_entrance, content, {
			'Content-Type': 'gzip',
			'Connection': 'Keep-Alive',
			'Accept-Encoding': 'gzip',
			'Host': 'hmma.baidu.com'
		}
